package net.rmi;

import java.io.Serializable;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import logic.Document;
import logic.Template;
import net.retrievers.AbstractRetriver;
import net.retrievers.Retriever;
import server.GlobalConfig;
import server.ServerRetriever;

@SuppressWarnings("unchecked")
public class RmiRetriever<E extends Serializable> extends AbstractRetriver<E>{
 
	
	
	private final Retriever r;
	private static RmiRetriever<Document> rmiRetriever;
	private static RmiRetriever<Template> rmiRetriever2;


	static Retriever<? extends Serializable> getRetriever(Class<? extends Serializable> s) throws Exception{
		if (Document.class.equals(s)) {
			rmiRetriever = new RmiRetriever<Document>(s, new ServerRetriever<Document>(GlobalConfig.DOCUMENT));
			return rmiRetriever;
		}
		if (Template.class.equals(s)) {
			rmiRetriever2 = new RmiRetriever<Template>(s, new ServerRetriever<Template>(GlobalConfig.TEMPLATE));
			return rmiRetriever2;
		}
		return null;

	}
	

	static void registerClass(Class<? extends Serializable> s) {
		try {
			Naming.rebind("rmi://127.0.0.1/r_"+s.getName(), UnicastRemoteObject.exportObject(getRetriever(s), 0));
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
	
	
	

	public RmiRetriever(Class<? extends Serializable> class1, Retriever r) {
		super(class1);
		this.r = r;

	}
	public String add(E obj, String key) throws RemoteException {
		return r.add(obj, key);
	}

	public void delete(String id, String key) throws RemoteException {
		r.delete(id, key);
	}


	public E get(String id, String key) throws RemoteException {
		return (E) r.get(id, key);
	}

	public void set(String id, E obj, String key) throws RemoteException {
		r.set(id, obj, key);
	}
}
